package com.jiexinyun.utils.excel;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.jiexinyun.listener.ExcelDataListener;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

public class EasyExcelUtils {

    /**
     * 导出 Excel
     */
    public static <T> void exportExcel(HttpServletResponse response,
                                       List<T> dataList,
                                       String fileName,
                                       String sheetName,
                                       Class<T> clazz) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        EasyExcel.write(response.getOutputStream(), clazz)
                .sheet(sheetName)
                .doWrite(dataList);
    }

    /**
     * 导入 Excel
     */
    public static <T> List<T> importExcel(MultipartFile file, Class<T> clazz) throws IOException {
        ExcelDataListener<T> listener = new ExcelDataListener<>(clazz);
        EasyExcel.read(file.getInputStream(), clazz, listener).sheet().doRead();
        return listener.getDataList();
    }

    /**
     * 导出 Excel
     */
    public static <T> void write(HttpServletResponse response,
                                       List<T> dataList,
                                       String fileName,
                                       String sheetName,
                                       Class<T> clazz) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        EasyExcel.write(response.getOutputStream(), clazz)
                .sheet(sheetName)
                .doWrite(dataList);
    }

}
